package com.webwork.mood.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

public class ExportUtil {
	
	/**
	  * 向客户端下载文件,弹出下载框.
	  * 
	  * @param response(HttpServletResponse)
	  * @param file(需要下载的文件)
	  * @param isDel(下载完成后是否删除该文件)
	  * @throws IOException 
	  */
	public static void exportFile(HttpServletResponse response, File file, boolean isDel) throws IOException {
		OutputStream out = null;
		InputStream in = null;

		//获得文件名
		String filename = URLEncoder.encode(file.getName(), "UTF-8");
		//定义输出类型(下载)
		response.setContentType("application/force-download");
		response.setHeader("Location", filename);
		//定义输出文件头
		response.setHeader("Content-Disposition", "attachment;filename=" + filename);
		try {
			out = response.getOutputStream();
			in = new FileInputStream(file.getPath());

			byte[] buffer = new byte[1024];
			int len;
			//System.out.println("this is first time begin*****");
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
			//System.out.println("this is first time end*****");
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
		}
		
		if (isDel) {
			//删除文件,删除前关闭所有的Stream.
//			file.delete();
			CommonTool.deleteFile(file);
		}
	}
	
	/**
	 * 压缩文件
	 * @param file//要压缩的文件
	 * @param zipFile 压缩后的文件
	 * @throws Exception
	 */
	public static void zip(File file, File zipFile) throws Exception {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
		zip(out, file, "");
		System.out.println("zip done");
		out.close();
	}

	private static void zip(ZipOutputStream out, File f, String base) throws Exception {
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base);
			}
		} else {
			out.putNextEntry(new ZipEntry(base + f.getName()));	//开始写入新的ZIP文件条目并将流定位到条目数据的开始处
			FileInputStream in = new FileInputStream(f);
			int b;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
		}
	}
	
}
